import { defineStore } from 'pinia';
import { getUserNotifications, getUnreadCount, markAsRead, markAllAsRead, deleteNotification, clearAllNotifications } from '../../api/notification';
import { ElMessage } from 'element-plus';

export const useAppStore = defineStore('app', {
  state: () => ({
    sidebarCollapsed: false,
    theme: localStorage.getItem('theme') || 'light',
    notifications: [],
    loading: false,
    currentBreadcrumb: []
  }),

  getters: {
    isDarkMode: (state) => state.theme === 'dark',
    hasUnreadNotifications: (state) => state.notifications.some(n => !n.read),
    unreadNotificationsCount: (state) => state.notifications.filter(n => !n.read).length
  },

  actions: {
    toggleSidebar() {
      this.sidebarCollapsed = !this.sidebarCollapsed;
    },

    toggleTheme() {
      this.theme = this.theme === 'light' ? 'dark' : 'light';
      localStorage.setItem('theme', this.theme);
      
      // 设置HTML元素的data-theme属性
      document.documentElement.setAttribute('data-theme', this.theme);
    },

    // 获取通知列表
    async fetchNotifications() {
      // 检查是否已登录，如果未登录，不请求通知
      const token = localStorage.getItem('token');
      if (!token) {
        console.log('未检测到登录状态，跳过通知请求');
        this.notifications = [];
        return false;
      }
      
      this.loading = true;
      try {
        console.log('开始获取通知列表');
        const response = await getUserNotifications();
        console.log('获取通知列表响应:', response);
        
        if (response && response.success) {
          // 处理通知数据，确保字段与前端一致
          this.notifications = (response.data || []).map(item => ({
            id: item.id,
            title: item.title,
            content: item.content,
            type: item.type,
            read: item.isRead, // 将后端的isRead映射为前端的read
            actionRoute: item.actionRoute,
            actionText: item.actionText,
            actionType: item.actionType,
            createTime: item.createTime,
            readTime: item.readTime,
            time: item.time,
            timestamp: new Date(item.createTime || Date.now()).getTime()
          }));
          console.log('更新通知列表:', this.notifications.length, '条通知');
          console.log('通知数据详情:', this.notifications);
          return true;
        } else {
          // 如果是认证相关错误则不显示错误消息（已在api层处理）
          if (response && response.message && 
             (response.message.includes('JWT') || 
              response.message.includes('token') || 
              response.message.includes('认证'))) {
            console.warn('认证错误，不显示错误消息');
            return false;
          }
          
          const errorMsg = response ? (response.message || '服务器返回错误') : '服务器没有响应';
          console.error('获取通知列表失败:', errorMsg);
          ElMessage.error(errorMsg);
          return false;
        }
      } catch (error) {
        // 如果是认证相关错误则不显示错误消息
        if (error.message && 
           (error.message.includes('JWT') || 
            error.message.includes('token') || 
            error.message.includes('认证'))) {
          console.warn('认证错误，不显示错误消息');
          return false;
        }
        
        console.error('获取通知列表失败', error);
        const errorMsg = error.message || '未知错误';
        ElMessage.error(`获取通知失败: ${errorMsg}`);
        return false;
      } finally {
        this.loading = false;
      }
    },

    // 获取未读消息数量
    async fetchUnreadCount() {
      try {
        const response = await getUnreadCount();
        if (response.success) {
          return response.data || 0;
        }
        return 0;
      } catch (error) {
        console.error('获取未读通知数量失败', error);
        return 0;
      }
    },

    // 添加本地通知（仅前端使用）
    addNotification(notification) {
      this.notifications.unshift({
        id: Date.now(),
        timestamp: Date.now(),
        read: false,
        ...notification
      });
    },

    // 标记通知为已读
    async markNotificationAsRead(id) {
      console.log(`准备标记通知${id}为已读`);
      try {
        const response = await markAsRead(id);
        console.log(`标记通知${id}为已读响应:`, response);
        
        if (response && response.success) {
          // 1. 立即在本地更新状态
          const notification = this.notifications.find(n => n.id === id);
          if (notification) {
            console.log(`在本地将通知${id}标记为已读`);
            notification.read = true;
          }
          
          // 2. 重新获取消息列表以保持同步（延迟执行，避免与本地状态冲突）
          setTimeout(async () => {
            console.log(`标记通知${id}已读后，延迟刷新通知列表`);
            await this.fetchNotifications();
          }, 500);
          
          return true;
        } else {
          console.error(`标记通知${id}为已读失败:`, response ? response.message : '未知错误');
          ElMessage.error(response ? (response.message || '标记通知为已读失败') : '标记通知为已读失败');
          return false;
        }
      } catch (error) {
        console.error('标记通知为已读失败', error);
        ElMessage.error('标记通知为已读失败: ' + (error.message || '未知错误'));
        return false;
      }
    },

    // 标记所有通知为已读
    async markAllNotificationsAsRead() {
      console.log('准备标记所有通知为已读');
      try {
        const response = await markAllAsRead();
        console.log('标记所有通知为已读响应:', response);
        
        if (response && response.success) {
          // 1. 立即在本地更新状态
          console.log('在本地将所有通知标记为已读');
          this.notifications.forEach(notification => {
            notification.read = true;
          });
          
          // 2. 重新获取消息列表以保持同步（延迟执行，避免与本地状态冲突）
          setTimeout(async () => {
            console.log('标记所有通知已读后，延迟刷新通知列表');
            await this.fetchNotifications();
          }, 500);
          
          return true;
        } else {
          console.error('标记所有通知为已读失败:', response ? response.message : '未知错误');
          ElMessage.error(response ? (response.message || '标记所有通知为已读失败') : '标记所有通知为已读失败');
          return false;
        }
      } catch (error) {
        console.error('标记所有通知为已读失败', error);
        ElMessage.error('标记所有通知为已读失败: ' + (error.message || '未知错误'));
        return false;
      }
    },

    setLoading(status) {
      this.loading = status;
    },

    setBreadcrumb(items) {
      this.currentBreadcrumb = items;
    },
    
    // 删除指定通知
    async deleteNotification(id) {
      try {
        const response = await deleteNotification(id);
        if (response.success) {
          // 从本地移除通知
          const index = this.notifications.findIndex(n => n.id === id);
          if (index !== -1) {
            this.notifications.splice(index, 1);
          }
          return true;
        } else {
          ElMessage.error(response.message || '删除通知失败');
          return false;
        }
      } catch (error) {
        console.error('删除通知失败', error);
        ElMessage.error('删除通知失败');
        return false;
      }
    },
    
    // 清空所有通知
    async clearAllNotifications() {
      try {
        const response = await clearAllNotifications();
        if (response.success) {
          // 清空本地通知列表
          this.notifications = [];
          return true;
        } else {
          ElMessage.error(response.message || '清空通知失败');
          return false;
        }
      } catch (error) {
        console.error('清空通知失败', error);
        ElMessage.error('清空通知失败');
        return false;
      }
    }
  }
}); 